<template>
    <ResourceForm @onFormSubmit="handleUpdate($event)" :resource="resource" :alert="alert" />
</template>
<script>
    import ResourceForm from "@/components/ResourceForm.vue";
    import { ref, watch, toRefs, reactive, onBeforeUnmount } from 'vue';
    import { updateResource } from '@/api/';
    export default {
        components: {
            ResourceForm
        },
        props: ['resource'],
        setup(props, context) {
            const uResource = ref(props.resource)
            watch(() => props.resource, (newVal, oldVal) => {
                uResource.value = newVal
            })
            onBeforeUnmount(() => {
                clearAlertTimeout();
            });
            const data = reactive({
                alert: {
                    success: null,
                    error: null,
                },
                timeoutId: null,
            })
            // method
            const initAlert = () => {
                return {
                    success: null,
                    error: null,
                };
            }
            const clearAlertTimeout = () => {
                data.timeoutId && clearTimeout(data.timeoutId);
            };

            const setAlert = (type, message) => {
                data.alert = initAlert();
                data.alert[type] = message;
                data.timeoutId = setTimeout(() => {
                    data.alert = initAlert();
                }, 3000);
            };
            const handleUpdate = async (uResource) => {
                try {
                    const updatedResource = await updateResource(
                        uResource.value.id,
                        uResource.value
                    );
                    context.emit("updateData", updatedResource);
                    setAlert("success", "Resource was updated");
                } catch (errorMessage) {
                    setAlert("error", errorMessage);
                }
            };
            return { ...toRefs(data),handleUpdate }
        }

    };
</script>